//
//  OverSeaListViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/11/27.
//

import UIKit
import MJRefresh
import SkeletonView

class OverSeaListViewController: BaseViewController {
    var emptyView: LYEmptyView!
    var filterPriceView: FilterPriceView! //价格view
    var filterTypeView: FilterCarTypeView!//车系
    var filterBrandView: FilterBrandView!//品牌
    
    var filterView: FilterView!
    var collectionView: UICollectionView!
    var dataArray = NSMutableArray()
    
    var filterData: FilterDataModel?
    var selectParam = SelectparameterModel()  //选中的参数
    var pageNo: NSInteger = 0
    var goTopBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "icon_suspend"))
        tempBtn.isHidden = true
        return tempBtn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("sea_car_title", comment: "海外车辆")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        filterView = FilterView.init()
        filterView.selectBlock = {[weak self] tag in
            self?.didSelectFilter(tag: tag)
        }
        self.view.addSubview(filterView)
        
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        let ww = (kScreenWidth - 38)/2
        layout.itemSize = CGSize(width: ww, height: 210)
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 100), collectionViewLayout: layout)
        self.collectionView.register(GoodsCollectionViewCell.self, forCellWithReuseIdentifier: "GoodsCollectionViewCell")
        self.collectionView.register(SkeletonCollectionCell.self, forCellWithReuseIdentifier: "SkeletonCollectionCell")
        self.collectionView.isSkeletonable = true
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.init(hex: 0xF8F9FA)
        collectionView.contentInset = UIEdgeInsets.init(top: 10, left: 14, bottom: 10, right: 14)
        self.view.addSubview(self.collectionView)
        
        goTopBtn.addTarget(self, action: #selector(goTopBtnAction), for: .touchUpInside)
        self.view.addSubview(self.goTopBtn)
        
        self.setUpNoData()
        self.addSnpLayout()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
        self.collectionView.showAnimatedGradientSkeleton()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if self.dataArray.count == 0 {
            self.fetchGetData()
            self.fetchGetFilterData()
        }
    }
    
    
    @objc func goTopBtnAction(){
        self.collectionView.scrollToTop(animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.didSelectFilter(tag: -1) //隐藏弹框
    }
    
    /*
     添加头部刷新
     */
    func addPullRefreash(){
        weak var weakSelf = self
        self.collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakSelf?.pageNo = 1
            weakSelf?.fetchGetData()
        })
    }
    
    //MARK: - 上拉加载更多
    private func addLoadMoreRefreash()  {
        weak var weakSelf = self
        let footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            weakSelf?.pageNo = self.pageNo + 1
            weakSelf?.fetchGetData()
        })
        self.collectionView.mj_footer = footer
    }
    
    private func addSnpLayout(){
        filterView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.height.equalTo(40)
            make.top.equalTo(NavBarHight)
        }
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(filterView.snp.bottom)
            make.bottom.equalTo(0)
        }
        
        self.goTopBtn.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.width.equalTo(34)
            make.height.equalTo(34)
            make.bottom.equalTo(-TabbarHeight)
        }
        self.view.layoutIfNeeded()
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
                //self.fetchGetData()
        }
        self.emptyView.actionBtnBackGroundColor = Theme.viewBkgGrayColor
        emptyView.centerX = kScreenWidth/2 - 14
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        emptyView.isHidden = true
        self.collectionView.ly_emptyView = self.emptyView
    }
    
    private func willShowSketchView(){
        if self.dataArray.count > 0  {
            self.emptyView.isHidden = true
        }else{
            self.emptyView.isHidden = false
        }
        self.collectionView.hideSkeleton()
    }
    
    ///获取商品列表
    private func fetchGetData(){
        var param = NSMutableDictionary() as! [String: String]
        param["pageNumber"] = "\(self.pageNo)"
        param["pageSize"] = "20"
        param["bodyCD"] = self.selectParam.bodyCD //车型
        if self.selectParam.brandId ?? 0 > 0 {
            //品牌编码
            param["brandid"] = "\(self.selectParam.brandId ?? 0)"
        }
        
        if self.selectParam.seriesId ?? 0 > 0 {
            param["katashiki"] = self.selectParam.seriesName   //车系
        }
        
        if self.selectParam.sellingPriceTypeCode != "" {
            param["sellingPriceTypeCode"] = self.selectParam.sellingPriceTypeCode //售价筛选code
        }
        
        if self.selectParam.yearMin ?? "" != "" {
            param["nenshikiStart"] = self.selectParam.yearMin ?? ""    //年份开始
            param["nenshikiEnd"] = self.selectParam.yearMax ?? ""     //年份结束
        }
        
        if self.selectParam.ascOrDesc != "" {
            param["ascOrDesc"] = self.selectParam.ascOrDesc     //0：升序，1：降序
        }
        
        if self.selectParam.orderProperty != "" {
            param["orderProperty"] = self.selectParam.orderProperty //0：价格，1：日期
        }
        
        //self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.goonetcarUserdCarPage(param: param),objectType: OverSeaListResModel.self) { data in
            
            self.view.handleLoading()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            let resultObj = data as! OverSeaListResModel
            if resultObj.code == "1" {
                let tempArr = resultObj.data?.content ?? []
                tempArr.forEach { item in
                    item.favoriteBlock = {[weak self] in
                        self?.requestFavorite(model: item)
                    }
                }
                if self.pageNo == 1 {
                    self.dataArray.removeAllObjects()
                }
                self.dataArray.addObjects(from: tempArr)
            }
            self.collectionView.reloadData()
            self.willShowSketchView()
        }error: { err in
            self.willShowSketchView()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.view.handleLoading()
        }
    }
    
    ///收藏取消收藏
    func requestFavorite(model: VehicleLisetModel){
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        var param = NSMutableDictionary() as! [String: String]
        param["usedcarId"] = "\(model.id ?? 0)"
        param["dataType"] = "2"
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.favorite(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                if model.favorite == false {
                    self.view.makeToast(message: MMLocalizedString("successful_collection", comment: "收藏成功"))
                    model.favorite = true
                }else{
                    self.view.makeToast(message: MMLocalizedString("uncollected", comment: "已取消收藏"))
                    model.favorite = false
                }
                self.collectionView.reloadData()
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        }error: { err in
            
        }
    }
    
    //MARK: - Antion
    @objc func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
    ///获取品牌参数
    private func fetchGetFilterData(){
        self.view.showLoadingHUDText()
        let param: [String: String] = [:]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.goonetcarSelectparameter(param: param), objectType: FilterDataResModel.self) { data in
            let resultObj = data as? FilterDataResModel
            if resultObj?.code == "1" {
                self.filterData = resultObj?.data
            }else{
                self.view.makeToast(message: resultObj?.msg ?? "")
            }
        }error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///选择顶部条件
    private func didSelectFilter(tag: NSInteger) {
        if self.filterPriceView?.showFlag == true {
            self.filterPriceView.handleClose()
            return
        }
        
        if self.filterTypeView?.showFlag == true {
            self.filterTypeView.handleClose()
            return
        }
        
        if self.filterBrandView?.showFlag == true {
            self.filterBrandView.handleClose()
            return
        }
        switch tag {
            case 0:
                //品牌
                filterBrandView = FilterBrandView.init(frame: CGRect.init(x: 0, y: filterView.frame.maxY, width: kScreenWidth, height: kScreenHeight - filterView.frame.maxY))
                filterBrandView.dataArray = self.filterData?.katashikiList ?? []
                filterBrandView.callBack = {[weak self] (brand, series) in
                    self?.pageNo = 1
                    if brand == nil {
                        //全部品牌
                        self?.selectParam.brandId = 0
                        self?.selectParam.seriesName = ""
                    }else{
                        self?.selectParam.brandId = NSInteger(brand?.brandId ?? "0")
                        self?.selectParam.seriesName = series
                    }
                    self?.fetchGetData()
                }
                UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(filterBrandView)
                filterBrandView.startAnimation()
            case 1:
                //价格
                var tempArr = self.filterData?.sellingPriceType ?? []
                let allTip = SellingPriceTypeData()
                allTip.desc = "不限"
                allTip.code = -1
                tempArr.insert(allTip, at: 0)
                
                filterPriceView = FilterPriceView.init(frame: CGRect.init(x: 0, y: filterView.frame.maxY, width: kScreenWidth, height: kScreenHeight - filterView.frame.maxY))
                filterPriceView.dataArray = tempArr
                filterPriceView.sellingPriceTypeCode = self.selectParam.sellingPriceTypeCode
                filterPriceView.callBack = {[weak self] index in
                    self?.pageNo = 1
                    
                    let arr = tempArr //self?.filterData?.sellingPriceType ?? []
                    if arr.count > index {
                        if index == 0 {
                            //不限
                            self?.selectParam.sellingPriceTypeCode = ""
                            self?.selectParam.priceMax = ""
                            self?.selectParam.priceGroup = ""
                            self?.fetchGetData()
                        }else{
                            let item = arr[index]
                            let priceArr = item.desc?.components(separatedBy: "-")
                            
                            let leftPrice = (priceArr?.first ?? "").removeAllSapce
                            let rightPrice = (priceArr?.last ?? "").removeAllSapce
                            self?.selectParam.priceMin = leftPrice
                            self?.selectParam.priceMax = rightPrice
                            self?.selectParam.sellingPriceTypeCode = "\(item.code ?? 0)"
                            self?.fetchGetData()
                        }
                    }
                }
                UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(filterPriceView)
                filterPriceView.startAnimation()
            case 2:
                //车型
                filterTypeView = FilterCarTypeView.init(frame: CGRect.init(x: 0, y: filterView.frame.maxY, width: kScreenWidth, height: kScreenHeight - filterView.frame.maxY))
                let cds = self.filterData?.bodyCDs ?? []
                filterTypeView.dataArray = cds
                //设置默认选中
                if self.selectParam.bodyCD == "" {
                    filterTypeView.selectIndex = 0
                }else{
                    //第一个不限
                    let tempIndex = cds.firstIndex(where: {$0 == self.selectParam.bodyCD }) ?? 0
                    filterTypeView.selectIndex = tempIndex + 1
                }
                //回调
                filterTypeView.callBack = {[weak self] (_, desc) in
                    self?.pageNo = 1
                    self?.selectParam.bodyCD = desc
                    self?.selectParam.carCategoryIds = desc
                    self?.fetchGetData()
                }
                UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(filterTypeView)
                filterTypeView.startAnimation()
            case 3:
                //更多筛选
                let vc = ScreenViewController()
                vc.selectModel = self.selectParam
                vc.originData = self.filterData
                vc.seaCarFlag = true
                vc.screeningConditionBlock = {[weak self] selectModel in
                    self?.selectParam = selectModel
                    self?.selectParam.bodyCD = selectModel.carCategoryIds
                    self?.pageNo = 1
                    self?.fetchGetData()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            default:
                ()
        }
    }
}

extension OverSeaListViewController: SkeletonCollectionViewDelegate, SkeletonCollectionViewDataSource {
    func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> SkeletonView.ReusableCellIdentifier {
        return "SkeletonCollectionCell"
    }
    
    
    ///SkeletonView 1组
    func numSections(in collectionSkeletonView: UICollectionView) -> Int {
        return 1
    }
    ///SkeletonView 20个item
    func collectionSkeletonView(_ skeletonView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    ///SkeletonView item
    func collectionSkeletonView(_ skeletonView: UICollectionView, skeletonCellForItemAt indexPath: IndexPath) -> UICollectionViewCell? {
        let cell = skeletonView.dequeueReusableCell(withReuseIdentifier: "SkeletonCollectionCell", for: indexPath) as! SkeletonCollectionCell
        cell.clipsToBounds = true
        return cell
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row]
            cell.setModel(model: model as! VehicleLisetModel)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row] as! VehicleLisetModel
            let vc = VehicleDetailsViewController()
            vc.id = "\(model.id ?? 0)"
            vc.seaCarFlag = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}


///选中品牌
extension OverSeaListViewController: BrandSearchViewDelegate {
    func selectBrandData(dataArray: NSMutableArray) {
        
    }
}


extension OverSeaListViewController: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        if offset <= kScreenHeight/2 {
            self.goTopBtn.isHidden = true
        }else{
            self.goTopBtn.isHidden = false
        }
    }
}
